package com.lnj.config;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
@Component
//基于Redis的对话记忆存储
public class PersistentChatMemoryStore implements ChatMemoryStore {
    private static final Logger logger = LoggerFactory.getLogger(PersistentChatMemoryStore.class);
    private static final String REDIS_KEY_PREFIX = "chat:memory:"; // Redis键前缀
    @Autowired
    private  StringRedisTemplate stringRedisTemplate;

    @PostConstruct
    public void init() {
        try {
            stringRedisTemplate.opsForValue().get("test");
            logger.info("Redis连接成功");
        } catch (Exception e) {
            logger.error("Redis连接失败", e);
            throw new IllegalStateException("无法连接到Redis服务器", e);
        }
    }


    //生成Redis存储键
    private String getKey(Object memoryId) {
        return REDIS_KEY_PREFIX + memoryId.toString();
    }

    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        String key = getKey(memoryId);
        String messageJson = stringRedisTemplate.opsForValue().get(key);
        if (messageJson == null || messageJson.isEmpty()) {
            return List.of();  // 无消息时返回空列表
        }
        return ChatMessageDeserializer.messagesFromJson(messageJson);

    }

    @Override
    public void updateMessages(Object memoryId  ,List<ChatMessage> messages) {
        String key = getKey(memoryId);
        String json = ChatMessageSerializer.messagesToJson(messages );
        stringRedisTemplate.opsForValue().set(key,json);
    }

    @Override
    public void deleteMessages(Object memoryId) {
        String key = getKey(memoryId);
        stringRedisTemplate.delete(key);
    }
}
